package com.atguigu.tingshu.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.order.enumeration.OrderStatusEnum;
import com.atguigu.tingshu.order.enumeration.PayWayEnum;
import com.atguigu.tingshu.order.mapper.OrderDetailMapper;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.context.OrderHandlerInterceptorContext;
import com.atguigu.tingshu.order.context.OrderTradeStrategyContext;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.order.startegy.OrderTradeStrategy;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private KafkaService kafkaService;


    @Override
    public OrderInfoVo trade(TradeVo tradeVo) {
        //判断三种购买方式
        String itemType = tradeVo.getItemType();
        OrderTradeStrategy orderTradeStrategy = OrderTradeStrategyContext.getOrderTradeStrategy(itemType);
        return orderTradeStrategy.trade(tradeVo);
    }

    @Override
    public String submitOrder(OrderInfoVo orderInfoVo) {
        OrderInfoVo infoVo = OrderHandlerInterceptorContext.entry(orderInfoVo);
        return infoVo.getTradeNo();
    }

    @Override
    public void canalOrder(String orderNo) {
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<OrderInfo>();
        queryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        //根据订单编号查询数据库
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        //判断订单状态
        if (SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())) { //表示未支付
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_CANCEL); //订单状态设置为已取消
            queryWrapper.eq(OrderInfo::getOrderStatus, SystemConstant.ORDER_STATUS_UNPAID); //更新条件 判断表中数据是否为未支付
            orderInfoMapper.update(orderInfo, queryWrapper);
        }

    }

    @Override
    public void orderPaySuccess(String orderNo) {
        //根据订单的编号查找订单数据
        OrderInfo orderInfo = getOrderInfoByOrderNo(orderNo);
        updateOrderStatus(orderNo, SystemConstant.ORDER_STATUS_PAID);
        //封装数据
        UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
        userPaidRecordVo.setOrderNo(orderNo);
        userPaidRecordVo.setUserId(orderInfo.getUserId());
        userPaidRecordVo.setItemType(orderInfo.getItemType());
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        List<Long> collect = orderDetailList.stream().map(OrderDetail::getItemId).collect(Collectors.toList());
        userPaidRecordVo.setItemIdList(collect);
        //向kafka中发送消息
        kafkaService.sendMsg(KafkaConstant.QUEUE_USER_PAY_RECORD, JSON.toJSONString(userPaidRecordVo));

    }


    //根据订单编号查询订单数据
    @Override
    public OrderInfo getOrderInfoByOrderNo(String orderNo) {
        //查询订单基本数据
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        //查询订单明细数据
        LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderDetail::getOrderId, orderInfo.getId());
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(lambdaQueryWrapper);
        //设置订单状态
        orderInfo.setOrderStatusName(OrderStatusEnum.getOrderStatusEnum(orderInfo.getOrderStatus()));
        // 设置支付方式
        orderInfo.setPayWayName(PayWayEnum.getPayWayEnum(orderInfo.getPayWay()));
        orderInfo.setOrderDetailList(orderDetails);
        return orderInfo;
    }

    @Override
    public IPage<OrderInfo> findUserPage(Long pageNum, Long limit) {
        Long userId = AuthContextHolder.getUserId();
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getUserId,userId);
        IPage<OrderInfo> page = new Page<>(pageNum, limit);
        this.page(page, queryWrapper);
        page.getRecords().forEach(orderInfo -> {
            orderInfo.setOrderStatusName(OrderStatusEnum.getOrderStatusEnum(orderInfo.getOrderStatus()));
            orderInfo.setPayWayName(PayWayEnum.getPayWayEnum(orderInfo.getPayWayName()));
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId, orderInfo.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(lambdaQueryWrapper);
            orderInfo.setOrderDetailList(orderDetails);
        });
        return page;
    }

    //修改订单数据
    private void updateOrderStatus(String orderNo, String orderStatus) {
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<OrderInfo>();
        queryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        orderInfo.setOrderStatus(orderStatus);
        orderInfoMapper.update(orderInfo, queryWrapper);
    }
}
